package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlyuan.open.scanner.dao.entity.OrderExceptionDO;
import com.wlyuan.open.scanner.dao.mapper.OrderExceptionMapper;
import com.wlyuan.open.scanner.repository.OrderExceptionRepository;
import com.wlyuan.open.scanner.utils.BatchSelectUtils;
import com.wlyuan.open.scanner.utils.StreamUtils;
import com.wlyuan.open.scanner.utils.enums.InvalidEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderExceptionRepositoryImpl implements OrderExceptionRepository {
    private final OrderExceptionMapper orderExceptionMapper;


    @Override
    public Map<Long, OrderExceptionDO> getOrderException(List<Long> orderId) {
        if (CollectionUtils.isEmpty(orderId)) {
            return Collections.emptyMap();
        }
        orderId = orderId.stream().distinct().collect(Collectors.toList());
        //分批查询
        var list = BatchSelectUtils.batch(orderId, this::select);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        //分组后，取最后一条
        return StreamUtils.maxByGroup(list, OrderExceptionDO::getExceptionOrderid, Comparator.comparing(OrderExceptionDO::getExceptionId));

    }

    @Override
    public OrderExceptionDO getOrderExceptionByOrderId(Long orderId) {
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderExceptionDO::getExceptionInvalid, InvalidEnum.ENABLE.getValue()).eq(OrderExceptionDO::getExceptionOrderid, orderId);
        var list = orderExceptionMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        //取最后一条
        return StreamUtils.max(list, Comparator.comparing(OrderExceptionDO::getExceptionId));
    }

    private List<OrderExceptionDO> select(List<Long> orderIds) {
        if (CollectionUtils.isEmpty(orderIds)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderExceptionDO::getExceptionInvalid, InvalidEnum.ENABLE.getValue()).in(OrderExceptionDO::getExceptionOrderid, orderIds);

        var list = orderExceptionMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list;
    }
}
